﻿Imports System
Imports System.Collections.Generic

Namespace System.Workflow.Runtime
    Friend NotInheritable Class SchedulerLockGuard
        Implements IDisposable
        ' Methods
        Friend Sub New(ByVal il As InstanceLock, ByVal w As WorkflowExecutor)
            Me.lg = il.Enter
            Me.workflowExec = w
        End Sub

        Public Sub Dispose()
            Dim eventList As New List([Of] SchedulerLockGuardInfo)(Me.workflowExec.EventsToFireList)
            Me.workflowExec.EventsToFireList.Clear
            Me.lg.Dispose
            SchedulerLockGuard.FireEvents(eventList, Me.workflowExec)
        End Sub

        Friend Shared Sub [Exit](ByVal il As InstanceLock, ByVal w As WorkflowExecutor)
            Dim eventList As New List([Of] SchedulerLockGuardInfo)(w.EventsToFireList)
            w.EventsToFireList.Clear
            il.Exit
            SchedulerLockGuard.FireEvents(eventList, w)
        End Sub

        Private Shared Sub FireEvents(ByVal eventList As List([Of] SchedulerLockGuardInfo), ByVal workflowExec As WorkflowExecutor)
            If (Not workflowExec.IsInstanceValid AndAlso ((workflowExec.WorkflowStatus = WorkflowStatus.Completed) OrElse (workflowExec.WorkflowStatus = WorkflowStatus.Terminated))) Then
                workflowExec.WorkflowInstance.DeadWorkflow = workflowExec
            End If
            Dim i As Integer
            For i = 0 To eventList.Count - 1
                Dim info As SchedulerLockGuardInfo = eventList.Item(i)
                Dim eventType As WorkflowEventInternal = info.EventType
                If (eventType <> WorkflowEventInternal.Suspended) Then
                    If (eventType = WorkflowEventInternal.Terminated) Then
                        goto Label_0057
                    End If
                    goto Label_008A
                End If
                workflowExec.FireWorkflowSuspended(CStr(info.EventInfo))
                [Continue] For
            Label_0057:
                If TypeOf info.EventInfo Is Exception Then
                    workflowExec.FireWorkflowTerminated(DirectCast(info.EventInfo, Exception))
                Else
                    workflowExec.FireWorkflowTerminated(CStr(info.EventInfo))
                End If
                [Continue] For
            Label_008A:
                workflowExec.FireWorkflowExecutionEvent(info.Sender, info.EventType)
            Next i
        End Sub


        ' Fields
        Private lg As InstanceLockGuard
        Private workflowExec As WorkflowExecutor
    End Class
End Namespace

